package example.pattern.iterator;

/**
 * @author Administrator
 *
 * @param <T>
 */
public class BookShelf<T> implements Iterable<T> {
	private int booksize = 0;
	private Object[] books = new Object[2];

	@Override
	public java.util.Iterator<T> iterator() {
		return new BookShelfIterator();
	}
	
	
	public void add(T book) {
		if (booksize == books.length) {
			Object[] newbook = new Object[books.length * 2];
			System.arraycopy(books, 0, newbook, 0, books.length);
			books = newbook;
		}
		books[booksize++] = book;
	}
	
	public void remove(T book) {
		int index = indexOf(book);
		remove(index);
	}
	
	public void remove(int index) {
		if (index > -1) {
			System.arraycopy(books, index + 1, books, index, books.length
					- index - 1);
			books[booksize-- -1] = null;
		}
	}
	
	public int indexOf(T book){
		int index = -1;
		int i = 0;
		for(Object b: books){
			if(b.equals(book)){
				index = i;
				break;
			}
			i++;
		}
		return index;
	}
	
	public int getLength(){
		return booksize;
	}

	private class BookShelfIterator implements java.util.Iterator<T>{
		private int index = 0;

		@Override
		public boolean hasNext() {
			return index < booksize;
		}

		
		@Override
		public T next() {
			return (T) books[index++];
		}

		@Override
		public void remove() {
			BookShelf.this.remove(--index);
		}

	}
}

